<script setup>
  import { computed, getCurrentInstance, nextTick, onMounted, reactive } from 'vue';
  import sheep from '@/sheep';
  import throttle from '@/sheep/helper/throttle';
  import { showAuthModal } from '@/sheep/hooks/useModal';

  const { proxy } = getCurrentInstance();

  const emits = defineEmits(['submit', 'bottomHeight', 'toggleMode', 'toggle', 'taskbarHeight']);

  const setImageStyle = (width, height) => {
    return {
      'width': width + 'rpx',
      'height': height + 'rpx',
    };
  };
  const setPlaceHolderStyle = () => {
    return {
      'font-family': 'PingFang SC, PingFang SC',
      'font-weight': '500',
      'font-size': '26rpx',
      'color': '#9F9F9F',
    };
  };
  const setInputStyle = () => {
    return {
      'font-family': 'PingFang SC, PingFang SC',
      'font-weight': '500',
      'font-size': '26rpx',
      'color': '#000000',
      'margin-left': '12rpx',
    };
  };
  const btnStyle = () => {
    return {
      backgroundColor: 'transparent',
      width: '100%',
      height: '100%',
      color: '#000000',
      border: 'none',
      marginRight: '16rpx',
    };
  };

  const state = reactive({
    is_audio: false,
    chatValue: '',
    bottomHeight: 0,
  });
  const props = defineProps({
    textInput: {
      type: Boolean,
      default: false,
    },
    showTaskbar: {
      type: Boolean,
      default: false,
    },
    shareFlag: {
      type: Boolean,
      default: false,
    },
    isShare: {
      type: Boolean,
      default: false,
    },
    friendInfo: {
      type: Object,
      default: () => ({}),
    },
    selectedQuantity: {
      type: Number,
      default: 0,
    },
  });

  const nc_image_path = computed(() => sheep.$store('AI').nc_image_path);

  onMounted(() => {
    // 监听键盘的高度
    uni.onKeyboardHeightChange(onKeyboardHeightChange);
  });

  const submit = (type) => {
    if (state.chatValue == '') return;
    emitsType('submit', {
      type,
      chatValue: state.chatValue,
    });
    state.chatValue = '';
  };

  const onKeyboardHeightChange = (res) => {
    // #ifdef MP
    const { height, duration } = res;
    // 键盘弹起
    if (height > 0) {
      nextTick(() => {
        state.bottomHeight = height;
        emits('bottomHeight', height, duration);
      });
    }
    // 键盘收回
    else {
      nextTick(() => {
        state.bottomHeight = height;
        emits('bottomHeight', height, duration);
      });
    }
    // #endif
  };

  // 获取元素的高度
  const getElementHeight = (id) => {
    return new Promise((resolve, reject) => {
      nextTick(() => {
        const query = uni.createSelectorQuery().in(proxy);
        query.select('#' + id).boundingClientRect((rect) => {
          resolve(rect.height);
        }).exec();
      });
    });
  };

  // 获取图片
  function selectPicture() {
    uni.chooseImage({
      count: 1,
      sourceType: ['album', 'camera'],
      success: (res) => {
        // 上传图片
        sheep.$api.app.upload(res.tempFilePaths[0]).then((res) => {
          // 发送图片
          emits('submit', {
            type: 'image',
            data: res,
          });
        });
      },
      fail: (err) => {
        console.log(err);
      },
    });
  }

  // 录音结束
  function endRecord(res) {
    // #ifdef H5
    console.log(res);
    emitsType('submit', {
      type: 'audio',
      data: res,
    });
    // #endif
    // #ifndef H5
    sheep.$api.app.upload(res.tempFilePath).then((res) => {
      // 发送语音
      emitsType('submit', {
        type: 'audio',
        data: res,
      });
    });
    // #endif
  }

  function emitsType(type, obj = {}) {
    emits(type, obj);
  }


  function shareTips() {
    if (props.selectedQuantity <= 0) {
      uni.showToast({
        title: '请先选择要分享的内容',
        icon: 'none',
      });
    }
  }

  const isLogin = computed(() => sheep.$store('user').isLogin);

  function immediateSession() {
    if (!isLogin.value) {
      showAuthModal();
      return;
    }
    uni.setStorageSync('chatInfo', JSON.stringify({
      id: props.friendInfo.id,
    }));
    sheep.$router.redirect('/pages/nc_chat/index');
  }
</script>

<template>
  <!-- 发送消息 -->
  <view id="chatBottom" class="buttonBottom flex flex-column align-center flex-sub" v-if="!isShare"
  <!-- #ifdef MP -->
  :style="{
  bottom:`${state.bottomHeight}px`
  }"
  <!-- #endif -->
  >
  <view class="w-100 flex flex-row align-center justify-between" v-if="!shareFlag">
    <view class="audio flex flex-row align-center justify-center" @tap="emitsType('toggle')"
          @click.stop="emitsType('taskbarHeight')">
      <image :style="[setImageStyle(47,47)]" :src="`${nc_image_path}/nc_add_white.png`"></image>
    </view>
    <view class="left flex flex-row align-center justify-center">
      <image v-if="textInput" :style="setImageStyle(51,51)" :src="`${nc_image_path}/nc_vioce.png`"
             @click="emitsType('toggleMode')"></image>
      <image v-else :style="setImageStyle(51,51)" :src="`${nc_image_path}/nc_chattext_icon.png`"
             @click="emitsType('toggleMode')"></image>
      <input v-if="textInput" v-model="state.chatValue" type="text" placeholder="请输入..."
             :style="setInputStyle()"
             :placeholder-style="setPlaceHolderStyle()"
             :adjust-position="false" confirm-type="send" :confirm-hold="true" @confirm="submit('text')">
      <view class="h-100" style="width: 86%;" v-else>
        <all-speech class="allSpeech" :btnStyle="btnStyle()" btnHoverFontcolor="#000000" btnHoverBgcolor="transparent"
                    @endRecord="endRecord"></all-speech>
      </view>
    </view>
    <view class="right flex flex-row align-center justify-center" @click.stop="throttle(submit('text'),1500)">
      发送
    </view>
  </view>
  <view class="w-100 flex flex-row align-center justify-around" v-else>
    <view class="unshare flex flex-row align-center justify-center" @click.stop="emitsType('unshare')">取消</view>
    <button v-if="selectedQuantity > 0" class="shareNow flex flex-row align-center justify-center" open-type="share"
            @tap.stop="emitsType('shareNow')">立即分享
    </button>
    <button v-else class="shareNow flex flex-row align-center justify-center" @tap.stop="shareTips">立即分享
    </button>
  </view>

  <view class="taskbar w-100 ss-p-y-20 ss-m-x-20" v-if="showTaskbar" @touchend.stop>
    <view class="picture flex flex-column justify-evenly align-center" @click.stop="selectPicture">
      <image :style="setImageStyle(62,62)" :src="`${nc_image_path}/nc_picture.png`"></image>
      <view class="text">图片</view>
    </view>
  </view>
  </view>
  <view id="chatBottom" class="buttonBottom flex flex-column align-center flex-sub" v-else
  <!-- #ifdef MP -->
  :style="{
  bottom:`${state.bottomHeight}px`
  }"
  <!-- #endif -->
  >
  <view class="shareW flex flex-row align-center justify-center" style="margin-left: 5rpx;"
        @click.stop="immediateSession">
    <image :src="`${nc_image_path}/nc_all_icon.png`" :style="setImageStyle(61,45)"></image>
    <view class="text_share" style="margin-left: 17rpx;">立即对话</view>
  </view>
  </view>
</template>

<style lang="scss">
  .buttonBottom {
    width: 750rpx;
    //position: fixed;
    //bottom: 0;
    //left: 50%;
    //transform: translateX(-50%);
    padding: 25rpx 23rpx 50rpx 0;
    background: #FFFFFF !important;

    .audio {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      background: #F5F5F5;
      margin-left: 20rpx;
    }

    .left {
      width: 450rpx;
      height: 80rpx;
      background: #F5F5F5;
      border-radius: 40rpx 40rpx 40rpx 40rpx;
      padding: 0 25rpx;

      input {
        width: 86%;
      }
    }

    .right {
      margin-right: 20rpx;
      width: 115rpx;
      height: 80rpx;
      background: #ff4206;
      border-radius: 40rpx 40rpx 40rpx 40rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 26rpx;
      color: #FFFFFF;
    }
  }

  .taskbar {
    width: 710rpx;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-column-gap: 19rpx;
  }

  .picture {
    width: 168rpx;
    height: 143rpx;
    background: #292A2E;
    border-radius: 8rpx 8rpx 8rpx 8rpx;

    .text {
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 400;
      font-size: 26rpx;
      color: #FFEBA3;
    }
  }

  .allSpeech {
    width: 100%;
    height: 100%;
  }

  .unshare {
    width: 237rpx;
    height: 80rpx;
    background: #F5F5F5;
    border-radius: 40rpx 40rpx 40rpx 40rpx;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 500;
    font-size: 26rpx;
    color: #4b4b4b;
  }

  .shareNow {
    width: 237rpx;
    height: 80rpx;
    background: linear-gradient(90deg, #FFECBE 0%, #F8D982 100%);
    border-radius: 40rpx 40rpx 40rpx 40rpx;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 500;
    font-size: 26rpx;
    color: #131315;
    margin: 0;
  }

  .shareW {
    width: 344rpx;
    height: 80rpx;
    background: linear-gradient(90deg, #FFECBE 0%, #F8D982 100%);
    border-radius: 40rpx 40rpx 40rpx 40rpx;
  }

  .text_share {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 500;
    font-size: 30rpx;
    color: #131315;
  }
</style>